<?php

/**
 * 案件调解
 * @author HelloWorld

 * 2019-8-8
 * UTF-8
 */
class CaseallocateController extends Controller_Base
{
    //案件分配记录列表
    public function IndexAction()
    {
        $request = $this->getRequest();
        $type = intval($request->getQuery('type', 1));
        $page = intval($request->getQuery('page', 1));
        $limit = intval($request->getQuery('limit', 10));
        $mediationOrganId  = intval($request->getQuery('mediationOrganId', 0));
        $assetsId  = intval($request->getQuery('assetsId', 0));
        $importRecordId = intval($request->getQuery('importRecordId', 0));
        $batshId = $request->getQuery('batshId', '');
        $litigantName = $request->getQuery('litigantName', '');
        $caseLabel = $request->getQuery('caseLabel', 0);
        $batchName = $request->getQuery('batchName', '');
        $id = $request->getQuery('id', '');
        $where = $this->getWhere();
        if($mediationOrganId){
            array_push($where,"mediationOrganId = ".$mediationOrganId);
        }
        if($assetsId){
            array_push($where,"assetsId = ".$assetsId);
        }
        if($importRecordId){
            array_push($where,"importRecordId = ".$importRecordId);
        }
        if($batshId){
            array_push($where,"batshId = '{$batshId}'");
        }
        if($caseLabel){
            if($caseLabel == 9){
                array_push($where,"caseLabel = 0");

            }else{
                array_push($where,"caseLabel = ".$caseLabel);
            }
        }
        if($litigantName){
            $caseId = $this->getCaseIdByLitigantName($litigantName);
            if($caseId){
                array_push($where,"id in ({$caseId})");
            }
        }
        if($batchName){
            array_push($where,"batchName = '{$batchName}'");
        }
        $add_begin_end = trim($this->getRequest()->getQuery('add_begin_end', ''));
        if ($add_begin_end){
            $date_tmp =  explode(" 到 ",$add_begin_end);
            $begin_date = $date_tmp[0];
            $end_date = $date_tmp[1];
            if (!empty($begin_date) || !empty($end_date)) {
                $begin_date = $begin_date ? $begin_date . " 00:00:00" : "";
                $end_date = $end_date ? $end_date . " 23:59:59" : "";
            }
            if ($end_date) {
                $end_date = strtotime($end_date);
                array_push($where, "addTime <= {$end_date}");

            }
            if ($begin_date) {
                $begin_date = strtotime($begin_date);
                array_push($where, "addTime >= {$begin_date}");
            }
        }

        if($id){
            array_push($where,"id = ".$id);
        }
        $page = $page ? $page : 1;
        $start = ($page - 1) * $limit;
        $query = [
            'id' => $id,
            'mediationOrganId' => $mediationOrganId,
            'assetsId' => $assetsId,
            'importRecordId' => $importRecordId,
            'batshId' => $batshId,
            'caseLabel' => $caseLabel,
            'litigantName' => $litigantName,
            'add_begin_end' => $add_begin_end,
            'batchName' => $batchName,
            'limit' => $limit,
        ];
        array_push($where, "sysStatus = 1 and caseStatus = 'case_allocate'");
        if($type == 1){
            $seacher = array(
                'where' => $where,
                'limit' => $limit,
                'start' => $start,
                'order' => 'cardId ASC , `id` ASC'
            );
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(array("*"), $seacher, true);
            $total = Module_Mediate_Case::getInstance()->getAllBySearch(array("count(*) as num"), array('where' => $where), true);
            $total = $total[0]['num'];

        }else{
            $seacher = array(
                'where' => $where,
                'limit' => $limit,
                'start' => $start,
                'order' => '`id` ASC',
                'group' => 'cardId',
            );
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['*','sum(debtTotal) as debtTotal','count(id) as caseNum'], $seacher, true);
            $total = Module_Mediate_Case::getInstance()->getGroupTotalBySearch(array("sum(debtTotal) as debtTotal"), array('where' => $where,'group' => 'cardId'), true);
            $total = $total[0]['num'];
        }
        $totalPage = ceil($total / $limit);
        //赋值调解部门
        $this ->getMediationOrgan();
        //赋值资产方
        $this ->getAssets();
        //赋值调解员
        $this ->getMediator(1);
        
        SmartyAdapter::assign('arrList', $cases);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('type', $type);
        SmartyAdapter::assign('page_query', http_build_query($query));

    }
    //分配案件
    public function allocateAction()
    {
        $allocateIds = $this->_request->getPost('allocateIds', '');
        $dataId = $this->_request->getPost('dataId', 0);
        $allocatetype = $this->_request->getPost('allocatetype', 0);
        $datatype = $this->_request->getPost('datatype', 0);
        if (!$allocateIds || !$dataId || !in_array($allocatetype,[1,2]) || !in_array($datatype,[1,2])) {
            AjaxTool::returnJsonData(4005);
        }
        if($datatype == 2){
           $history_case =  Module_Mediate_Case::getInstance()->getAllBySearch(['cardId'],['where'=>["id in ($allocateIds)"]]);
           $cardId =  "'".implode("','",array_column($history_case,'cardId'))."'";
           $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['id'],['where'=>["caseStatus = 'case_allocate'","cardId in ({$cardId})"]]);
           $allocateIds = implode(',',array_column($cases,'id'));
        }

        $time = time();
        //分配到个人
        if($allocatetype == 1){
            $mediator = Module_User_Administrator::getInstance()->getItemById($dataId);
            if (!$mediator) {
                AjaxTool::returnJsonData(4001);
            }
            //分配
            $res = Module_Mediate_Case::getInstance()->saveByIds([
                'mediatorId'=>$dataId,
                'mediatorName'=>$mediator['name'],
                'mediationOrganId'=>$mediator['mediationOrganId'],
                'allocateTime'=>time(),
                'caseStatus'=>'case_mediate',
                'updateTime'=>$time,
            ], $allocateIds);
            //分配成功，添加日志记录
            if($res){
                $id_arr = explode(',', $allocateIds);
                foreach ($id_arr as $id){
                    $data = [
                        'caseId' => $id,
                        'status' => 'case_allocate_mediator',
                        'operationUid' => $this->admin['id'],
                        'operationName' => $this->admin['name'],
                        'operationContent' =>"案件分配",
                        'remark' => "分配案件到 {$mediator['name']} 调解员",
                        'createTime' => $time,
                    ];
                    $post_data = [
                        'type' => 'Module_Task_Case',
                        'method' => 'addOperateLog',
                        'data' => $data
                    ];
                    @Module_Queue_Base::addQueue($post_data);
                }
            }

        }else {
            $mediationOrgan = Module_InfoBase_MediationOrgan::getInstance()->getItemById($dataId);
            if (!$mediationOrgan) {
                AjaxTool::returnJsonData(4001);
            }
            //分配
            $res = Module_Mediate_Case::getInstance()->saveByIds([
                'mediationOrganId'=>$dataId,
                'updateTime'=>$time,
            ], $allocateIds);
            //分配成功，添加日志记录
            if($res){
                $id_arr = explode(',', $allocateIds);
                foreach ($id_arr as $id){
                    $data = [
                        'caseId' => $id,
                        'status' => 'case_allocate_organ',
                        'operationUid' => $this->admin['id'],
                        'operationName' => $this->admin['name'],
                        'operationContent' =>"案件分配",
                        'remark' => "分配案件到 {$mediationOrgan['name']} 调解部门",
                        'createTime' => $time,
                    ];
                    $post_data = [
                        'type' => 'Module_Task_Case',
                        'method' => 'addOperateLog',
                        'data' => $data
                    ];
                    @Module_Queue_Base::addQueue($post_data);
                }
            }
        }
        AjaxTool::returnJsonData(200);
    }
}
